<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\UniversityRequest;
use App\Models\University;
use App\Transformers\UniversityTransformer;
use Illuminate\Http\Request;

class UniversityController extends Controller
{
    public function index(Request $request, University $university)
    {
        $university = $university->newQuery();
        if ($request->input('name')) {
            $university->where('name', 'like', '%'.$request->input('name').'%');
        }
        if ($request->input('type') || $request->input('type') === 0 || $request->input('type') === '0') {
            $university->where('type', $request->input('type'));
        }
        $universitys = $university->orderBy('created_at', 'desc')->paginate(20);

        return $this->response->paginator($universitys, new UniversityTransformer());
    }

    public function store(UniversityRequest $request)
    {
        $univeristy = University::create([
            'name' => $request->name,
            'type' => $request->type,
        ]);

        return $this->response->item($univeristy, new UniversityTransformer())
            ->setStatusCode(201);
    }

    public function update(UniversityRequest $request, University $university)
    {
        $university->update([
            'name' => $request->name,
            'type' => $request->type,
        ]);

        return $this->response->item($university, new UniversityTransformer());
    }

    public function delete(University $university)
    {
        $university->delete();

        return $this->response->noContent();
    }
}
